package com.dao;

import java.io.Serializable;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

import com.bean.Person;

public class PersonDAO extends HibernateDaoSupport {
	@SuppressWarnings("unchecked")
	public List<Person> findByProperties(Map<String, Object> args) {
		try {
			StringBuilder queryString = new StringBuilder();
			Iterator<Entry<String, Object>> iter = args.entrySet().iterator();

			if (iter.hasNext()) {
				Map.Entry<String, Object> entry = iter.next();
				queryString.append("from Person as p where p." + entry.getKey()
						+ "= ? ");
				while (iter.hasNext()) {
					entry = (Map.Entry<String, Object>) iter.next();
					queryString.append("and p." + entry.getKey() + "= ? ");
				}
			} else {
				return null;
			}

			return getHibernateTemplate().find(queryString.toString(),
					args.values().toArray());
		} catch (RuntimeException re) {
			throw re;

		}
	}

	public Serializable save(Person person) {
		return getHibernateTemplate().save(person);
	}

	public void delete(Person person) {
		getHibernateTemplate().delete(person);
	}

	public Person findById(Serializable id) {
		Person person = (Person) getHibernateTemplate().get(
				Person.class.getName(), id);
		return person;
	}

	public Person merge(Person person) {
		Person result = (Person) getHibernateTemplate().merge(person);
		return result;
	}

	@SuppressWarnings("unchecked")
	public List<Person> findAll() {
		try {
			return getHibernateTemplate().find("from Person ");
		} catch (RuntimeException re) {
			throw re;
		}
	}
}
